<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Albert <albert_p@foxmail.com>
// +----------------------------------------------------------------------
namespace App\Console;

use App\Modules\Em\Logics\CommonLogic;
use App\Modules\Tool\Controllers\Sms;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use JYPHP\Core\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class NoticeServerCommand extends Command
{
    const KEY = 'notice_server_pid';

    protected $name = "server:notice";

    protected $desc = "通知推送服务";

    protected $serverConfig = [];

    public function configure()
    {
        parent::configure();
        $this->addArgument(
            "operation",
            InputArgument::REQUIRED,
            "操作类型有: start 开启服务 , dev 开发者模式开启服务 , kill 关闭服务 , restart 重启服务"
        );
        $this->serverConfig = config('notice.configure');
    }

    public function handle()
    {
        $operations = [
            'start',
            'dev',
            'kill',
            'restart'
        ];
        $operation = $this->input->getArgument('operation');
        if (!(method_exists($this, $operation) && in_array($operation, $operations))) {
            throw new \Exception("'" . $operation . "'" . "  not operation");
        }
        $this->output->writeln($operation . "ing ...");
        $this->app->call(
            [
                $this,
                $operation
            ]
        );
    }

    public function start()
    {
        $serv = new \Swoole\Websocket\Server(config("notice.host"), config("notice.port"));

        $serv->on('Start', function ($server) {
            Cache::forever(self::KEY, $server->master_pid);
//            echo $server->master_pid;
        });

        $serv->on('Open', function ($server, $req) {
            echo "connection open: " . $req->fd."\n";
        });

        $serv->on('Message', function ($server, $frame) {
            $data = json_decode($frame->data, true);
            if ($data['method'] == 'login') {
                Cache::forever('notifications' . $data['data']['user_id'], $frame->fd);
                Cache::forever('notifications_fd' . $frame->fd, $data['data']['user_id']);
            } else if ($data['data']['notifications'] && is_array($data['data']['notifications'])) {
                $receive_id = Cache::get('notifications' . $data['data']['user_id']);
                //在线并且没有优先级直接推送，1发送短信2发送邮件3什么都不发送，存进去数据表。登录进来再提醒
                if (!empty($receive_id) && $data['data']['priority'] == 0) {
                    //写进去消息表
                    DB::table('notifications')->insert($data['data']['notifications']);
                    $server->push($receive_id, $data['data']['receive_msg']);
                } elseif($data['data']['priority'] == 1) {
                    $phone = DB::table('member')->where('id', $data['data']['user_id'])->value('telephone');
                    if (!empty($phone)) {
                        Sms::instance($phone)->content($data['data']['receive_msg']['code'],empty($data['data']['receive_msg']['param']) ? [] : $data['data']['receive_msg']['param'])->send();
                    }
                } elseif ($data['data']['priority'] == 2) {
                    //发送邮件
                } else {
                    //写进去消息表
                    DB::table('notifications')->insert($data['data']['notifications']);
                }
            }
        });

        $serv->on('Close', function ($server, $fd) {
            Cache::forget('notifications' . Cache::get('notifications_fd' . $fd));
            Cache::forget('notifications_fd' . $fd);
            echo "connection close: " . $fd."\n";
        });
        unset($data);
        $serv->start();
    }

    public function restart()
    {

    }

    public function kill()
    {
        exec(escapeshellcmd(
            "kill" . ' '
            . Cache::get(self::KEY)
        ));
    }

    public function dev()
    {
        $this->serverConfig['daemonize'] = false;
        $this->start();
    }
}